/**
 * 闲来无事做，做个自动搭建路由以及基础文件的微型脚手架
 * 慢更
 * 希望写完有人看到可以用起来 埋个彩蛋
 * created by Wu，2019-01-26
 */
const fs = require('fs');
const path = require('path');
const routePath = path.resolve(__dirname,'./src/routes');
const menuJson = path.resolve(__dirname,'./src/static/i18n');
const menuRoute = path.resolve(__dirname,'./src/routes/menuRoute.js');
const showMenu = path.resolve(__dirname,'./src/routes/showMenu.js');

var o = {
  isNormal: false,  //是否在normal模式
  isFirstLevel: false, //是否是1级的目录
  icon: '',  //1级目录的icon的type
  parentKey: '',  //2级目录的parentKey
  key: '',  //该目录的key
  zh: '',  //目录的中文
  en: ''  //目录的英文
};

var time = 0;

init();

function init(){
  process.stdin.setEncoding('utf8');
  process.stdout.write('需要增加的是否是员工模式页面（1是，0不是）:');
  process.stdin.on('readable', () => {
    var chunk = process.stdin.read();
    if(typeof chunk === 'string'){
      chunk = chunk.slice(0,-1);
      time += 1;
    }
    if(chunk === ''){
      process.stdin.emit('end');
    }
    if (chunk !== null) {
      switch (time){
        case 1:
          o.isNormal = chunk === '1';
          process.stdout.write('是否是一级路由（1是，0不是）:');
          return;
        case 2:
          o.isFirstLevel = chunk === '1';
          o.isFirstLevel ? process.stdout.write('请输入icon:') : process.stdout.write('请输入parentName:');
          return;
        case 3:
          o.isFirstLevel ? o.icon = chunk : o.parentKey = chunk;
          process.stdout.write('请输入key:');
          return;
        case 4:
          o.key = chunk;
          process.stdout.write('请输入目录中文:');
          return;
        case 5:
          o.zh = chunk;
          process.stdout.write('请输入目录英文:');
          return;
        default:
          o.en = chunk;
          process.stdout.write('请输入回车退出');
          return;
      }
    }
  });

  process.stdin.on('end', () => {
    process.exit(0);
  });

  process.on('exit',() => {
    if(o.isFirstLevel){
      let targetPath = path.join(routePath,`${o.isNormal ? 'normal' : 'admin'}/${o.key}.js`);
      let content = `const ${hump(o.key)} = {\n  key: '${o.key}',\n  icon: '${o.icon}'${o.isNormal ? '' : ',\n  admin: true'},\n  subMenu: [],\n};\n\nexport default ${hump(o.key)};`;
      fs.writeFileSync(targetPath,content);
      // TODO 创建基础文件 目前就加了一个文件夹 有什么需要可以跟我提
      let menuContent = fs.readFileSync(menuRoute,'utf-8');
      if(o.isNormal){
        let addReg = new RegExp('//非管理员模式下菜单','g');
        menuContent = menuContent.replace(addReg,(target) => {
          target = `${target}\nimport ${hump(o.key)} from 'routes/normal/${o.key}'  //${o.zh}`;
          return target;
        });
        let showReg = new RegExp('/\\*\\* 以下是管理员模式下的菜单 \\*\\*/','g');
        menuContent = menuContent.replace(showReg,(target) => {
          target = `${hump(o.key)},  //${o.zh}\n  ${target}`;
          return target;
        });
      }else{
        let addReg = new RegExp('//管理员模式下菜单','g');
        menuContent = menuContent.replace(addReg,(target) => {
          target = `${target}\nimport ${hump(o.key)} from 'routes/${o.isNormal ? 'normal' : 'admin'}/${o.key}'  //${o.zh}`;
          return target;
        });
        let showReg = new RegExp('const menu = \\[([.\n\\s\\S]+?)\\]','g');
        menuContent = menuContent.replace(showReg,(target,$1) => {
          $1 += `${$1}\n  ${hump(o.key)}  //${o.zh}\n`;
          target = `const  menu = [${$1}]`;
          return target;
        });
      }
      fs.writeFileSync(menuRoute,menuContent);
      let showContent = fs.readFileSync(showMenu,'utf-8');
      let showMenuReg = new RegExp('\\],\n  oldList:{}','g');
      showContent = showContent.replace(showMenuReg,(target) => {
        target = `  {\n      key: '${o.key}', //${o.zh}\n    },\n  ${target}`;
        return target;
      });
      fs.writeFileSync(showMenu,showContent);
      !fs.existsSync(`./src/containers/${o.key}`) && fs.mkdirSync(`./src/containers/${o.key}`);
      addJSON();
    }else{
      let targetPath = path.join(routePath,`${o.isNormal ? 'normal' : 'admin'}/${o.parentKey}.js`);
      let content = fs.readFileSync(targetPath,'utf-8');
      let reg = new RegExp('subMenu: \\[(([^\\[]*)(\\[([^\\]]*)\\]([^\\[]*))*)\\]','g');
      content = content.replace(reg,(target,$1) => {
        $1[$1.length - 1] !== ',' && ($1 += ',');
        $1 += `\n    {\n      key: '${o.key}',\n      url: '/main/${o.parentKey}/${o.key}',\n      components: ${componentComp(o.key)},\n      parent: '${o.parentKey}'\n    }\n`;
        target = `subMenu: [${$1}  ]`;
        return target;
      });
      // TODO 现在支持一个模版界面 例如起始时间 有的是startDate 有的是beginDate 后台统一了就可以吧搜索和表格加进来
      let importReg = new RegExp('import(\\s)*([a-zA-Z]+)(\\s)*from(\\s)*(\'|")([^\'"]+)(\'|")(;)?\n','mg');
      let importContent = '';
      let s = importReg.exec(content);
      while(s){
        if(s[0] && s[0] !== ''){
          importContent += s[0];//匹配的中文放入输出流的字符串中
        }
        s = importReg.exec(content);//换到下个index
      };
      content = content.replace(importReg,'');
      importContent += `import ${componentComp(o.key)} from "containers/${o.parentKey}/${o.key}/${o.key}";\n`;
      content = importContent + content;
      fs.writeFileSync(targetPath,content);
      addJSON();
      !fs.existsSync(`./src/containers/${o.parentKey}/${o.key}`) && fs.mkdirSync(`./src/containers/${o.parentKey}/${o.key}`);
      let fileContent = `import React from 'react'\nimport {connect} from 'react-redux'\n\nclass ${hump(o.key)} extends React.Component{\n  constructor(props){\n    super(props);\n    this.state = {\n      \n    };\n  }\n\n  componentWillMount(){\n    \n  }\n\n  render(){\n    const {} = this.state;\n    return (\n      <div>\n        \n      </div>\n    )\n  }\n}\n\nfunction mapStateToProps(state)  {\n  return {\n    \n  }\n}\n\nexport default connect(mapStateToProps)(${hump(o.key)});`;
      fs.writeFileSync(`./src/containers/${o.parentKey}/${o.key}/${o.key}.js`,fileContent);
      let showContent = fs.readFileSync(showMenu,'utf-8');
      let showReg = new RegExp(`{([^k]+)key:(\\s)*'${o.parentKey}'([^l]+)list: \\[([^\\]]+)\\]([^}]*)}`,'g');
      showContent = showContent.replace(showReg,(target,$1,$2,$3,$4,$5) => {
        $4 =  $4.replace(new RegExp("'([^']+)'(,)?",'g'),(str,s1) => {
          str = `'${s1}',`;
          return str;
        });
        $4 = `${$4}  '${o.key}'  //${o.zh}\n      `;
        target = `{${$1}key:${$2 ? $2 : ''}'${o.parentKey}'${$3}list: [${$4}]${$5}}`;
        return target;
      });
      fs.writeFileSync(showMenu,showContent);
    }
  });

  // 本来想用子进程一个一个处理输入的东西 想想没有必要 这边脚本很简单不像实时的聊天室 下面放一个子进程的例子
  // process.on('exit', function() {
  //   const p = child_process.exec(
  //     'node child', // 执行的命令
  //     {},
  //     (err, stdout, stderr) => {
  //       if (err) {
  //         console.log('err:', err, err.code, err.signal);
  //       }
  //       console.log('stdout:', stdout);
  //       console.log('stderr:', stderr);
  //     }
  //   );
  //   console.log('child pid:', p.pid);
  // });
}

function hump(arg) {
  arg = arg.replace(/-(\w)/g, (all, letter) => {
  return letter.toUpperCase();
  });
  return arg;
}

function componentComp(arg) {
  arg = hump(arg);
  arg = arg.replace(/(\w)/, (all, letter) => {
    return letter.toUpperCase();
  });
  arg += 'Comp';
  return arg;
}

function addJSON() {
  let zhPath = path.join(menuJson,`zh_CN/menu.json`);
  let enPath = path.join(menuJson,`en_US/menu.json`);
  let zhContent = fs.readFileSync(zhPath,'utf-8');
  let reg = new RegExp(':(\\s)?"([^"]*)"(,)?','g');
  zhContent = zhContent.replace(reg,(target,$1,$2) => {
    target = `:${$1 ? $1 : ''}"${$2}",`;
    return target;
  });
  zhContent = zhContent.replace('}',`  "menu.${o.key}": "${o.zh}"\n}`);
  fs.writeFileSync(zhPath,zhContent);
  let enContent = fs.readFileSync(enPath,'utf-8');
  enContent = enContent.replace(reg,(target,$1,$2) => {
    target = `:${$1 ? $1 : ''}"${$2}",`;
    return target;
  });
  enContent = enContent.replace('}',`  "menu.${o.key}": "${o.en}"\n}`);
  fs.writeFileSync(enPath,enContent);
}
